<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="filters" ref="searchForm">
            <el-form-item prop="userName">
              <el-input v-model="filters.userName" :clearable="true" placeholder="用户名"></el-input>
            </el-form-item>
            <el-form-item prop="userCode">
              <el-input v-model="filters.userCode" :clearable="true" placeholder="用户编号"></el-input>
            </el-form-item>
            <el-form-item prop="fullName">
              <el-input v-model="filters.fullName" placeholder="姓名"> </el-input>
            </el-form-item>
            <el-form-item prop="phone">
              <el-input type="number" v-model="filters.phone" placeholder="电话号码"></el-input>
            </el-form-item>
            <el-form-item prop="managerLevels">
              <el-select v-model="filters.managerLevels" placeholder="管理员类别">
                <el-option v-for="item in levelsList" :value="item.value" :label="item.label" :key="item.value"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="businessId">
              <el-select v-model="filters.businessId" placeholder="所属商户" clearable filterable>
                <el-option v-for="item in businessList" :value="item.id" :label="item.name" :key="item.id"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
          <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()" size="mini">新增商户管理员</el-button>
        </div>
      </el-col>
    </el-row>
    <el-row ref="tableRow">
      <el-table :data="tableList" :fit="true">
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column prop="userCode" align="center" label="编号" width="200"></el-table-column>
        <el-table-column prop="userName" align="center" label="用户名" width="200"></el-table-column>
        <el-table-column prop="nickName" align="center" label="昵称" width="200"></el-table-column>
        <el-table-column prop="managerLevels" align="center" label="管理员类别" width="150">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" :type="formatLevel(scope.row.managerLevels)">
                {{ formatLevels(scope.row.managerLevels) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="fullName" label="姓名" width="120"></el-table-column>
        <el-table-column label="性别" align="center" width="80">
          <template slot-scope="scope">
            <span>
              {{ scope.row.sex == 1 ? '男' : '女' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="手机号" align="center" width="120" prop="phone"> </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" effect="dark" :type="formatStates(scope.row.state)">
                {{ formatState(scope.row.state) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="创建人" prop="createUserName"> </el-table-column>
        <el-table-column align="center" label="创建时间" prop="createDate"> </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-row>
              <el-button v-has="permissionCheck" @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
              <el-dropdown trigger="click" size="small">
                <el-button type="primary"><i class="fa fa-list-ul"></i>更多</el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item v-has="permissionEdit" @click.native="handleClickEditor(scope.row)">编辑</el-dropdown-item>
                  <el-dropdown-item v-has="permissionBindDepart" @click.native="handleBindingDepart(scope.row)"> 绑定部门 </el-dropdown-item>
                  <el-dropdown-item v-has="permissionUpStatus" @click.native="handleIsDisable(scope.row)">{{ scope.row.state === 0 ? '启用' : '禁用' }}</el-dropdown-item>
                  <el-dropdown-item v-has="permissionDelete" @click.native="handleClickDelete(scope.row)">删除</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>
    </el-row>

    <el-dialog width="500px" center :visible.sync="bindDeparts.showBindDepart" title="绑定部门">
      <div style="text-align: center">
        <el-cascader
          style="width: 100%"
          :props="{ value: 'departId', label: 'departName', checkStrictly: true, multiple: true }"
          :options="bindDeparts.departList"
          v-model="bindDeparts.departIds"
          placeholder="请选择部门"
        ></el-cascader>
      </div>
      <div slot="footer">
        <el-button @click="confrimBindDepart" type="primary">确定</el-button>
        <el-button @click="bindDeparts.showBindDepart = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import * as message from '@/constants/message';
import ManagerBusinessApi from '@/api/business/manager';
import BusinessDepartApi from '@/api/business/depart';
import BusinessApi from '@/api/business/business';
export default {
  name: 'UserManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      filters: {
        userCode: '',
        managerLevels: '',
        businessId: '',
        userName: '',
        fullName: '',
        phone: '',
      },
      tableList: [],

      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 20,
      },
      levelsList: [
        { value: 0, label: '商户' },
        { value: 1, label: '部门' },
        { value: 2, label: '组' },
        { value: 3, label: '岗位' },
      ],
      businessList: [],
      bindDeparts: {
        showBindDepart: false,
        departIds: [],
        managerId: '',
        departList: [],
      },
      permissionCheck: 'SYSTEM_MANAGER_BUSINESS_MANAGER_LIST_SEE',
      permissionAdd: 'SYSTEM_MANAGER_BUSINESS_MANAGER_LIST_ADD',
      permissionEdit: 'SYSTEM_MANAGER_BUSINESS_MANAGER_LIST_EDIT',
      permissionUpStatus: 'SYSTEM_MANAGER_BUSINESS_MANAGER_LIST_STATE',
      permissionDelete: 'SYSTEM_MANAGER_BUSINESS_MANAGER_LIST_DELETE',
      permissionBindDepart: 'SYSTEM_MANAGER_BUSINESS_MANAGER_LIST_BIND_DEPART',
    };
  },
  created() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  activated() {
    if (this.$route.meta.keepAlive) {
      this.listTable();
    }
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    init() {
      this.getDepartList();
      this.listTable();
      this.getTableHeight();
      this.getBusinessList();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },
    getTableHeight() {
      this.$nextTick(function () {
        this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        window.onresize = () => {
          this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        };
      });
    },
    listTable() {
      let data = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
        userCode: this.filters.userCode,
        managerLevels: this.filters.managerLevels,
        userName: this.filters.userName,
        fullName: this.filters.fullName,
        phone: this.filters.phone,
        businessId: this.filters.businessId,
      };
      this.fetchData(data);
    },
    formatState(cellValue) {
      if (cellValue === -1) {
        return '删除';
      } else if (cellValue === 0) {
        return '禁用';
      } else if (cellValue === 1) {
        return '启用';
      }
    },
    formatStates(cellValue) {
      if (cellValue === -1) {
        return 'danger';
      } else if (cellValue === 0) {
        return 'info';
      } else if (cellValue === 1) {
        return 'success';
      }
    },
    formatLevel(cellValue) {
      if (cellValue === 0) {
        return 'danger';
      } else if (cellValue === 1) {
        return 'warning';
      } else if (cellValue === 2) {
        return 'success';
      } else if (cellValue === 3) {
        return 'info';
      }
    },
    formatLevels(cellValue) {
      if (cellValue === 0) {
        return '商户';
      } else if (cellValue === 1) {
        return '部门';
      } else if (cellValue === 2) {
        return '组';
      } else if (cellValue === 3) {
        return '岗位';
      }
    },
    // 获取商户列表
    getBusinessList() {
      BusinessApi.listIdNameVo().then((res) => {
        this.businessList = res.data;
      });
    },
    getDepartList() {
      BusinessDepartApi.listMangerTree().then((res) => {
        this.setDisabled(res.data);
        this.bindDeparts.departList = res.data;
      });
    },
    // 设置部门中哪些不可选
    setDisabled(list) {
      list.forEach((item) => {
        if (!item.power) {
          item.disabled = true;
        }
        if (item.children) {
          this.setDisabled(item.children);
        }
      });
    },
    handleBindingDepart(row) {
      this.bindDeparts.departIds = row.strDepartIds.split(',');
      this.bindDeparts.managerId = row.managerId;
      this.getDepartIds();
      this.bindDeparts.showBindDepart = true;
    },
    // 格式化部门departId为cascader所需的格式
    getDepartIds() {
      const departIds = [];
      this.bindDeparts.departIds.forEach((item) => {
        const val = this.$Utils.filterTreeToArr(this.bindDeparts.departList, { departId: item }, 'departId').map((item) => item.departId);
        departIds.push(val);
      });
      this.bindDeparts.departIds = departIds;
    },
    confrimBindDepart() {
      if (this.bindDeparts.departIds.length == 0) {
        this.$message.error('请至少选择一个部门');
        return;
      }

      const params = {
        ids: this.bindDeparts.departIds.map((item) => item.at(-1)),
        id: this.bindDeparts.managerId,
      };
      this.$confirm('确定批量绑定部门', '提示', {}).then((res) => {
        ManagerBusinessApi.setManagerBinding(params).then((res) => {
          this.$Utils.notifySuccess('绑定成功');
          this.bindDeparts.showBindDepart = false;
          this.listTable();
        });
      });
    },
    handleSizeChange(size) {
      this.page.pageSize = size;
      this.listTable();
    },
    handleCurrentChange(val) {
      this.page.pageNo = val;
      this.listTable();
    },
    handleClickEditor(row) {
      this.$router.push({ path: '/business/managerBusinessEdit', query: { id: row.managerId } });
    },
    handleClickDetail(row) {
      this.$router.push({ path: '/business/managerBusinessDetail', query: { id: row.managerId } });
    },
    handleClickAdd() {
      this.$router.push({ path: '/business/managerBusinessAdd' });
    },
    handleIsDisable(row) {
      let currentState = row.state === 0 ? 1 : 0;
      let newStateName = row.state === 0 ? message.MSG_CONFIRM_ENABLE : message.MSG_CONFIRM_DISABLE;
      this.$confirm(newStateName, message.TITLE_PROMPT, {}).then(() => {
        let data = {
          id: row.managerId,
          state: currentState,
        };
        ManagerBusinessApi.updateManagerState(data).then((res) => {
          row.state = currentState;
          this.$Utils.notifySuccess();
        });
      });
    },
    handleClickDelete(row) {
      this.$confirm(message.MSG_CONFIRM_DELETE, message.TITLE_PROMPT, {}).then(() => {
        let data = {
          id: row.managerId,
          state: -1,
        };
        ManagerBusinessApi.deleteManager(data).then((res) => {
          this.listTable();
          this.$Utils.notifySuccess();
        });
      });
    },
    fetchData(data) {
      // this.$emit('show-loading', true);
      ManagerBusinessApi.listManager(data)
        .then((res) => {
          this.tableList = res.data.list;
          this.page.pageTotal = res.data.total;
          // this.$emit('show-loading', false);
        })
        .catch((error) => {
          // this.$emit('show-loading', false);
        });
    },
    onSearch() {
      this.page.pageNo = 1;
      this.listTable();
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.onSearch();
    },
  },
};
</script>
<style lang="scss">
@import '@/assets/css/views/content.scss';
</style>
